{% extends "base_generic.html" %}

{% block content %}

<h1>标题: {{ book.title }}</h1>

<p><strong>作者:</strong> <a href="{{ book.author.get_absolute_url }}">{{ book.author }}</a></p>
<p><strong>摘要:</strong> {{ book.summary }}</p>
<p><strong>ISBN:</strong> {{ book.isbn }}</p>
<p><strong>语言:</strong> {{ book.language }}</p>
<p><strong>类别:</strong> {{ book.genre.all|join:", " }}</p>

<div style="margin-left:20px;margin-top:20px">
<h4>副本</h4>

{% for copy in book.bookinstance_set.all %}
  <hr>
  <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'd' %}text-danger{% else %}text-warning{% endif %}">{{ copy.get_status_display }}</p>
  {% if copy.status != 'a' %}<p><strong>预计归还日期:</strong> {{copy.due_back}}</p>{% endif %}
  <p><strong>版本:</strong> {{copy.imprint}}</p>
  <p class="text-muted"><strong>编号:</strong> <a href="{{ copy.get_absolute_url }}">{{copy.id}}</a></p>
{% empty %}
  <p>图书馆没有这本书的副本。</p>
{% endfor %}
</div>

<div class="mt-4">
  <h4>评分与评价</h4>
  <div class="d-flex align-items-center mb-3">
    <div class="me-3">
      <span class="fs-3 fw-bold">{{ book.average_rating|floatformat:1 }}</span>
      <span class="text-muted">({{ book.rating_count }} 评价)</span>
    </div>
    <div class="text-warning">
      {% for i in "12345"|make_list %}
        {% if forloop.counter <= book.average_rating|floatformat:0 %}
          <i class="bi bi-star-fill"></i>
        {% else %}
          <i class="bi bi-star"></i>
        {% endif %}
      {% endfor %}
    </div>
  </div>

  {% if user.is_authenticated %}
    <div class="card mb-4">
      <div class="card-body">
        <h5 class="card-title">添加评价</h5>
        <form method="post" action="{% url 'add_review' book.id %}">
          {% csrf_token %}
          <div class="mb-3">
            <label for="rating" class="form-label">评分</label>
            <select class="form-select" id="rating" name="rating" required>
              <option value="1">1 - 很差</option>
              <option value="2">2 - 一般</option>
              <option value="3">3 - 良好</option>
              <option value="4">4 - 很好</option>
              <option value="5">5 - 极好</option>
            </select>
          </div>
          <div class="mb-3">
            <label for="comment" class="form-label">评论</label>
            <textarea class="form-control" id="comment" name="comment" rows="3" required></textarea>
          </div>
          <button type="submit" class="btn btn-primary">提交评价</button>
        </form>
      </div>
    </div>
  {% else %}
    <div class="alert alert-info" role="alert">
      <a href="{% url 'login' %}?next={{ request.path }}">登录</a> 后可以添加评价
    </div>
  {% endif %}

  <div class="reviews mb-4">
    {% for review in book.reviews.all %}
      <div class="card mb-3">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-center">
            <h6 class="card-subtitle mb-2 text-muted">{{ review.user.username }}</h6>
            <div class="text-warning">
              {% for i in "12345"|make_list %}
                {% if forloop.counter <= review.rating %}
                  <i class="bi bi-star-fill"></i>
                {% else %}
                  <i class="bi bi-star"></i>
                {% endif %}
              {% endfor %}
            </div>
          </div>
          <p class="card-text">{{ review.comment }}</p>
          <p class="card-text"><small class="text-muted">{{ review.created_at|date:"Y-m-d H:i" }}</small></p>
        </div>
      </div>
    {% empty %}
      <p>暂无评价</p>
    {% endfor %}
  </div>

  <div class="d-flex gap-2 mb-4">
    {% if user.is_authenticated %}
      <button id="likeBtn" class="btn btn-outline-primary" data-book-id="{{ book.id }}">
        <i class="bi bi-heart"></i> <span id="likeCount">{{ book.like_count }}</span> 喜欢
      </button>
      <button id="favoriteBtn" class="btn btn-outline-secondary" data-book-id="{{ book.id }}">
        <i class="bi bi-bookmark"></i> 收藏
      </button>
    {% else %}
      <a href="{% url 'login' %}?next={{ request.path }}" class="btn btn-outline-primary">
        <i class="bi bi-heart"></i> 喜欢
      </a>
      <a href="{% url 'login' %}?next={{ request.path }}" class="btn btn-outline-secondary">
        <i class="bi bi-bookmark"></i> 收藏
      </a>
    {% endif %}

    {% if book.purchase_url %}
      <a href="{{ book.purchase_url }}" class="btn btn-success ms-auto" target="_blank">
        <i class="bi bi-cart"></i> 购买此书
      </a>
    {% endif %}
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // 喜欢功能
      const likeBtn = document.getElementById('likeBtn');
      if (likeBtn) {
        likeBtn.addEventListener('click', function() {
          const bookId = this.dataset.bookId;
          fetch(`{% url 'toggle_like' 0 %}`.replace('0', bookId), {
            method: 'POST',
            headers: {
              'X-CSRFToken': getCookie('csrftoken'),
              'Content-Type': 'application/json'
            }
          })
          .then(response => response.json())
          .then(data => {
            document.getElementById('likeCount').textContent = data.like_count;
            const icon = likeBtn.querySelector('i');
            if (data.status === 'liked') {
              likeBtn.classList.remove('btn-outline-primary');
              likeBtn.classList.add('btn-primary');
              icon.classList.remove('bi-heart');
              icon.classList.add('bi-heart-fill');
            } else {
              likeBtn.classList.remove('btn-primary');
              likeBtn.classList.add('btn-outline-primary');
              icon.classList.remove('bi-heart-fill');
              icon.classList.add('bi-heart');
            }
          });
        });
      }

      // 收藏功能
      const favoriteBtn = document.getElementById('favoriteBtn');
      if (favoriteBtn) {
        favoriteBtn.addEventListener('click', function() {
          const bookId = this.dataset.bookId;
          fetch(`{% url 'toggle_favorite' 0 %}`.replace('0', bookId), {
            method: 'POST',
            headers: {
              'X-CSRFToken': getCookie('csrftoken'),
              'Content-Type': 'application/json'
            }
          })
          .then(response => response.json())
          .then(data => {
            const icon = favoriteBtn.querySelector('i');
            if (data.status === 'favorited') {
              favoriteBtn.classList.remove('btn-outline-secondary');
              favoriteBtn.classList.add('btn-secondary');
              icon.classList.remove('bi-bookmark');
              icon.classList.add('bi-bookmark-fill');
            } else {
              favoriteBtn.classList.remove('btn-secondary');
              favoriteBtn.classList.add('btn-outline-secondary');
              icon.classList.remove('bi-bookmark-fill');
              icon.classList.add('bi-bookmark');
            }
          });
        });
      }

      // 获取CSRF Token辅助函数
      function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
          const cookies = document.cookie.split(';');
          for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
            }
          }
        }
        return cookieValue;
      }
    });
  </script>

{% endblock %}


{% block sidebar %}
  {{ block.super }}

  {% if perms.catalog.change_book or perms.catalog.delete_book %}
  <hr>
  <ul class="sidebar-nav">
    {% if perms.catalog.change_book %}
      <li><a href="{% url 'book-update' book.id %}">更新图书</a></li>
    {% endif %}
    {% if not book.bookinstance_set.all and perms.catalog.delete_book %}
      <li><a href="{% url 'book-delete' book.id %}">删除图书</a></li>
    {% endif %}
    </ul>
  {% endif %}

{% endblock %}

<div class="col-md-6">
    <h4>可用副本</h4>
    {% if book.bookinstance_set.all %}
        <ul class="list-group">
            {% for copy in book.bookinstance_set.all %}
                <li class="list-group-item d-flex justify-content-between align-items-center">
                    <div>
                        <span class="badge {% if copy.status == 'a' %}bg-success{% elif copy.status == 'm' %}bg-danger{% else %}bg-warning{% endif %}">
                            {{ copy.get_status_display }}
                        </span>
                        {% if copy.status != 'a' %}
                            <span class="ms-2"><i class="fas fa-calendar-alt me-1"></i> 归还日期: {{ copy.due_back }}</span>
                        {% endif %}
                        <span class="ms-2"><i class="fas fa-hashtag me-1"></i> {{ copy.imprint }}</span>
                    </div>
                    {% if user.is_staff and perms.catalog.can_mark_returned %}
                        <a href="{% url 'renew-book-librarian' copy.id %}" class="btn btn-sm btn-outline-secondary"><i class="fas fa-sync-alt me-1"></i> 续借</a>
                    {% endif %}
                </li>
            {% endfor %}
        </ul>
    {% else %}
        <p class="alert alert-info"><i class="fas fa-info-circle me-2"></i> 暂无评论，来发表第一条评论吧！</p>
    {% endif %}
</div>
<div class="mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h5><i class="fas fa-comments me-2"></i> 用户评论</h5>
        <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#reviewModal">
            <i class="fas fa-pencil-alt me-1"></i> 写评论
        </button>
    </div>
    
    <div class="d-flex mb-4">
        <button class="btn btn-sm btn-outline-danger me-3 like-button" data-book-id="{{ book.id }}">
            <i class="fas fa-heart{% if user_liked %} text-danger{% endif %} me-1"></i> 点赞 ({{ book.like_count }})
        </button>
        <button class="btn btn-sm btn-outline-secondary favorite-button" data-book-id="{{ book.id }}">
            <i class="fas fa-bookmark{% if user_favorited %} text-primary{% endif %} me-1"></i> 收藏
        </button>
    </div>
    
    <!-- 评论列表 -->
    {% for review in book.review_set.all %}
        <!-- 评论内容 -->
    {% empty %}
        <p class="text-muted"><i class="fas fa-comment-slash me-2"></i> 暂无评论，来发表第一条评论吧！</p>
    {% endfor %}
</div>
